let { api, imgUrl } = require("./../../utils/api.js");
let optionsDishId = ""; //记录上一页面传入的菜单ID
// let timer = ""; //用于关闭抖动的评价图标
Page({
  data: {
    imgUrl,
    indicatorDots: true,
    autoplay: true,
    circular: true,
    interval: 3000,
    duration: 1000,
    score1: "fa fa-star star", //评价星级的class值
    score2: "fa fa-star-half-o half-star",
    score3: "fa fa-star def-star",
    zan1: "fa fa-thumbs-o-up",
    zan2: "fa fa-thumbs-o-up zan-icon",
    score: 4, //评分,
    isHaveEvaluation: false,
    release: false,
    refresh: false //控制页面返回是否进行页面刷新
  },
  onLoad: function(options) {
    optionsDishId = Number(options.dishId);
    // 获取菜系详情
    this.getDishDetails(options.dishId);
  },

  onShow: function() {
    // 获取菜系评价
    this.getDishEvaluation(optionsDishId);
    // this.releaseShake();
  },

  onHide: function() {
    // clearInterval(timer);
  },

  onPullDownRefresh: function() {
    // 下拉刷新数据
    // 获取菜系详情
    this.getDishDetails(optionsDishId);
    // 获取菜系评价
    this.getDishEvaluation(optionsDishId);
    setTimeout(() => {
      wx.stopPullDownRefresh();
      wx.showToast({
        title: "成功加载最新评论 ！",
        icon: "none",
        duration: 2000
      });
    }, 1500);
  },

  // 获取菜系详情
  getDishDetails: function(dishId) {
    let that = this;
    wx.request({
      url: api + "getDishDetail.do",
      method: "POST",
      data: {
        dishId
      },
      success: function(res) {
        if (res.data.status === 1) {
          that.setData({
            dishData: res.data.data,
            dishId, //用作去评价时传递给菜品评价页面
            dishName: res.data.data.dishName
          });
        } else {
          wx.showToast({
            title: "获取菜系详情失败，请稍后重试!",
            icon: "none",
            duration: 2000
          });
        }
      },
      fail: function(res) {
        console.log(res);
        wx.showToast({
          title: "网络错误，请稍后重试",
          icon: "none",
          duration: 2000
        });
      }
    });
  },

  // 获取菜系评价
  getDishEvaluation: function(dishId) {
    let that = this;
    let obj = {
      userId: wx.getStorageSync("userInfo").userId,
      dishId
    };
    // console.log(obj);
    wx.request({
      url: api + "getDishEvaluation.do",
      method: "POST",
      data: obj,
      success: function(res) {
        console.log(res.data);
        if (res.data.status === 1) {
          console.log("菜系详情：我刷新啦！");
          if (res.data.data !== null) {
            let { evaluationDishHelperList, tag, score } = res.data.data;
            if (evaluationDishHelperList.length) {
              let tagList = that.filerTag(tag);
              let newData = evaluationDishHelperList.map(val => {
                // 截取08-09 12:00格式的日期
                val.evaluationDish.evaluationDate = val.evaluationDish.evaluationDate.slice(
                  5,
                  17
                );
                val.evaluationDish.evaluationContent = decodeURIComponent(
                  val.evaluationDish.evaluationContent
                );
                return val;
              });
              that.setData({
                tagList,
                evaluationList: evaluationDishHelperList,
                score,
                isHaveEvaluation: true
              });
            }
          } else {
            console.log(that.data.dishName + ":暂无评论");
          }
        } else {
          wx.showToast({
            title: "获取菜系评价失败，请稍后重试!",
            icon: "none",
            duration: 2000
          });
        }
      },
      fail: function(res) {
        console.log(res);
        wx.showToast({
          title: "网络错误，请稍后重试",
          icon: "none",
          duration: 2000
        });
      }
    });
  },

  //筛选返回的用户评论数据中的评论标签数组，标签数大于0方可展示
  filerTag: function(tag) {
    let arr = [];
    for (let keys in tag) {
      if (keys !== "id" && keys !== "dishId" && tag[keys]) {
        let obj = {
          name: "",
          num: 0
        };
        switch (keys) {
          case "weishengbuhao":
            obj.name = "卫生不好";
            obj.num = tag[keys];
            break;
          case "fenliangshao":
            obj.name = "分量少";
            obj.num = tag[keys];
            break;
          case "taina":
            obj.name = "太辣";
            obj.num = tag[keys];
            break;
          case "taixian":
            obj.name = "太咸";
            obj.num = tag[keys];
            break;
          case "taitian":
            obj.name = "太甜";
            obj.num = tag[keys];
            break;
          case "taisuan":
            obj.name = "太酸";
            obj.num = tag[keys];
            break;
          case "taiku":
            obj.name = "太苦";
            obj.num = tag[keys];
            break;
          case "wuwei":
            obj.name = "无味";
            obj.num = tag[keys];
            break;
          case "ganjingweisheng":
            obj.name = "干净卫生";
            obj.num = tag[keys];
            break;
          case "maixiangbucuo":
            obj.name = "卖相不错";
            obj.num = tag[keys];
            break;
          case "weidaoyiban":
            obj.name = "味道一般";
            obj.num = tag[keys];
            break;
          case "fenliangzu":
            obj.name = "分量足";
            obj.num = tag[keys];
            break;
          case "weidaozan":
            obj.name = "味道赞";
            obj.num = tag[keys];
            break;
          case "youyingyang":
            obj.name = "有营养";
            obj.num = tag[keys];
            break;
        }
        arr.push(obj);
      }
    }
    return arr;
  },

  // 图片预览
  imgPreview: function(e) {
    let src = e.currentTarget.dataset.src;
    let srcArr = [src];
    let current = src;
    if (Object.prototype.toString.call(src) == "[object Array]") {
      srcArr = src.map(val => {
        return imgUrl + val;
      });
      current = e.currentTarget.dataset.current;
    }
    wx.previewImage({
      current,
      urls: srcArr // 需要预览的图片http链接列表
    });
  },

  // 评论点赞
  changZan: function(e) {
    let { evaluationList } = this.data;
    let newAllComment = evaluationList;
    //页面展示已经点赞（取消赞）的操作（假象）
    for (let val of newAllComment) {
      if (val.evaluationDish.evaluationId === Number(e.currentTarget.id)) {
        val.evaluationDish.isIlike
          ? val.evaluationDish.likesnum--
          : val.evaluationDish.likesnum++;
        val.evaluationDish.isIlike = !val.evaluationDish.isIlike;
      }
    }
    this.setData({
      evaluationList: newAllComment
    });
    //真是的进行接口点赞操作后台处理
    wx.request({
      url: api + "likeDishEvaluation.do",
      method: "POST",
      data: {
        userId: wx.getStorageSync("userInfo").userId,
        evaluationId: e.currentTarget.id
      },
      success: function(res) {
        if (res.data.status === 1) {
          let text = res.data.message === "取消赞成功" ? "已取消" : "已点赞";
          wx.showToast({
            title: text,
            icon: "none",
            duration: 2000
          });
        } else {
          wx.showToast({
            title: "我在开小差，请稍后再试！",
            icon: "none",
            duration: 2000
          });
        }
      },
      fail: function(res) {
        wx.showToast({
          title: "网络请求错误，请稍后再试！",
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  //  点击菜系介绍的评价数，滚动到对应的评论界面
  rollComment: function() {
    const query = wx.createSelectorQuery();
    query
      .select("#comment")
      .boundingClientRect(function(res) {
        wx.pageScrollTo({
          scrollTop: res.top
        });
      })
      .exec();
  },
  // 去评价页面
  goHome: function() {
    wx.switchTab({
      url: "./../index/index"
    });
  },
  // 去评价页面
  goRelease: function() {
    let { dishName, dishId } = this.data;
    wx.navigateTo({
      url:
        "./../releaseEvaluation/releaseEvaluation?dishName=" +
        dishName +
        "&dishId=" +
        dishId
    });
  }

  //评价图标抖动
  // releaseShake: function() {
  //   let that = this;
  //   timer = setInterval(function() {
  //     that.setData({
  //       release: !that.data.release
  //     });
  //   }, 1000);
  // }
});
